package ru.ya.kolemik.servcmd.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class SyntaxFilter extends AbstractFilter {
    
    private String [] dynamicResources = new String [] {"/JSP/"};
    
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        log.debug("SyntaxFilter - set character encoding.");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String uri = (String) httpRequest.getAttribute("javax.servlet.include.request_uri");
        if (uri == null) {
            uri = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        } else {
            uri = uri.substring(httpRequest.getContextPath().length());
        }
        log.debug("SyntaxFilter - URI: " + uri);
        if (uri != null) {
            for (String prefix : dynamicResources) {
                if (uri.startsWith(prefix)) {
                    log.debug("Динамический ресурс");
                    chain.doFilter(request, response);
                }
            }            
           httpRequest.getRequestDispatcher("/").include(request,
                    response);
        } else {
            throw new ServletException("Unexpected request!" + httpRequest.getRequestURI());
        }
    }
    
}
